/**
 * 组合函数通用实现
 */

function ddCompose(...fns) {
  //先遍历出所有的函数
  var length = fns.length
  for (var i = 0; i < length; i++) {
    var fn = fns[i]
    if (typeof fn !== 'function') {
      //必须传入一个函数，否则报错
      throw new TypeError('Excepted a function')
    }
  }
  
  //返回一个组合函数
  return function (...args) {
    var index = 0
    var res = length ? fns[index].apply(this, args) : args
    while (++index < length) {
      res = fns[index].call(this, res)
    }
    return res
  }
  
}

function double(x) {
  return x * 2
}

function square(x) {
  return x ** 2
}

var foo = ddCompose(double, square)
console.log(foo(2))
